require "udp-biz"

mulIp = "224.0.211.211"
mulListenPort = 6100
mulGatewayPort = 6000
--excludeWifi={}
--currWifiConfig = nil

exclude = false
failTime = 0


isListen = false
isStart = false
conn = nil
srv = nil



------------------------------------------B3----------------------------------------------------
---
function __b3_connectToCloudWifiConfig(wifiConfig) 
    if(exclude) then
        exclude = false
        failTime = 0
        return false
    end
    __registerWifiEvent(__b3_wifi_success, __b3_wifi_fail)
    wifi.setmode(wifi.STATION)
    print("connecting to cloud wifi:"..wifiConfig["ssid"].." password:"..wifiConfig["password"])
    wifi.sta.config(wifiConfig["ssid"], wifiConfig["password"])
    return true
end 

function __b3_wifi_success(config)
    print("__b3_wifi_success...")
    isConnect = true
    errors = ""
    if(srv) then
            srv:close()
    end
    if(conn) then
        conn:close()
    end
    srv = net.createServer(net.UDP)
    conn = net.createConnection(net.UDP, 0)
    conn:connect(mulGatewayPort,mulIp)
    srv:on("receive", handler)
    srv:listen(mulListenPort)
    net.multicastJoin(wifi.sta.getip(), mulIp)
    print(mulListenPort)
    print(mulIp)
    print(wifi.sta.getip())
    isListen = true
    isStart = true
    __sendRegister()
    heartTmr()
    excludeWifi={}
end
function __b3_wifi_fail(config)
    print("__b3_wifi_fail...")
    isConnect = false
    
    if(heardTimer) then 
        heardTimer:unregister()
        heardTimer = nil
    end
    if(isListen) 
    then
        srv:close()
        conn:close()
        conn = nil
        srv = nil
        isListen = false
    end
    failTime = failTime + 1
    if(failTime >= 10) then
        local error = "wifi["..config["SSID"].."] connect fail."
        errors = errors..error
        exclude = true
        wifi.sta.getap(1, connectToWifi)
    --else
        --local tryAgainTimer = tmr.create()
        --tryAgainTimer:register(15000, tmr.ALARM_SINGLE, tryConnect)
        --tryAgainTimer:start()
    end
end
